package com.it.schoolhomeos.controller;

import com.it.schoolhomeos.entity.ClassInfo;
import com.it.schoolhomeos.entity.User;
import com.it.schoolhomeos.service.ClassService;
import com.it.schoolhomeos.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api")
@Tag(name = "班级管理", description = "班级信息的增删改查接口")
public class ClassController {

    @Autowired
    private ClassService classService;
    
    @Autowired
    private UserService userService;

    @GetMapping("/admin/classes/list")
    @Operation(summary = "获取班级简化列表", description = "获取所有班级的简化信息，用于下拉选择")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Map<String, Object>> getClassList() {
        List<ClassInfo> classes = classService.findAll();
        List<Map<String, Object>> simplifiedClasses = classes.stream()
                .map(classInfo -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", classInfo.getId());
                    map.put("name", classInfo.getName());
                    map.put("grade", classInfo.getGrade());
                    if (classInfo.getTeacher() != null) {
                        map.put("teacherName", classInfo.getTeacher().getName());
                    }
                    return map;
                })
                .collect(Collectors.toList());

        Map<String, Object> response = new HashMap<>();
        response.put("status", "success");
        response.put("message", "获取班级列表成功");
        response.put("data", simplifiedClasses);
        
        return ResponseEntity.ok(response);
    }

    @GetMapping("/admin/classes")
    @Operation(summary = "管理员获取班级列表", description = "管理员获取所有班级的完整信息")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Map<String, Object>> getAllClassesForAdmin(
            @Parameter(description = "搜索关键词（班级名称、年级、班主任姓名）") 
            @RequestParam(required = false) String keyword,
            @Parameter(description = "页码") 
            @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页大小") 
            @RequestParam(defaultValue = "10") int size) {
        
        System.out.println("接收到查询请求 - 关键字: " + keyword + ", 页码: " + page + ", 每页大小: " + size);
        
        List<ClassInfo> classes;
        if (keyword != null && !keyword.trim().isEmpty()) {
            System.out.println("执行关键字查询: " + keyword);
            classes = classService.findByKeyword(keyword);
            System.out.println("查询结果数量: " + (classes != null ? classes.size() : 0));
        } else {
            System.out.println("执行查询所有班级");
            classes = classService.findAll();
            System.out.println("查询结果数量: " + (classes != null ? classes.size() : 0));
        }
        
        Map<String, Object> response = new HashMap<>();
        response.put("status", "success");
        response.put("message", "获取班级列表成功");
        response.put("data", classes);
        
        return ResponseEntity.ok(response);
    }

    /**
     * 为班级分配班主任
     * 
     * @param classId 班级ID
     * @param teacherId 教师ID
     * @return 操作结果
     */
    @PutMapping("/admin/classes/{classId}/teacher")
    @Operation(summary = "分配班主任", description = "管理员为班级分配班主任")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Map<String, Object>> assignTeacherToClass(
            @PathVariable Long classId,
            @RequestBody Map<String, Long> requestBody) {
        
        try {
            Long teacherId = requestBody.get("teacherId");
            
            if (teacherId == null) {
                return ResponseEntity.badRequest().body(Map.of(
                    "status", "error",
                    "message", "请提供教师ID"
                ));
            }
            
            // 获取班级信息
            ClassInfo classInfo = classService.findById(classId);
            if (classInfo == null) {
                return ResponseEntity.badRequest().body(Map.of(
                    "status", "error",
                    "message", "班级不存在"
                ));
            }
            
            // 获取教师信息
            User teacher = userService.findTeacherById(teacherId);
            if (teacher == null) {
                return ResponseEntity.badRequest().body(Map.of(
                    "status", "error",
                    "message", "教师不存在"
                ));
            }
            
            // 设置班主任
            classInfo.setTeacher(teacher);
            
            // 保存更新
            ClassInfo updatedClass = classService.update(classInfo);
            
            return ResponseEntity.ok(Map.of(
                "status", "success",
                "message", "班主任分配成功",
                "data", updatedClass
            ));
            
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of(
                "status", "error",
                "message", "班主任分配失败: " + e.getMessage()
            ));
        }
    }

    @GetMapping("/teacher/classes")
    @Operation(summary = "教师获取班级列表", description = "教师获取所有班级的列表")
    @PreAuthorize("hasRole('TEACHER')")
    public ResponseEntity<Map<String, Object>> getAllClasses() {
        List<ClassInfo> classes = classService.findAll();
        return ResponseEntity.ok(Map.of(
            "status", "success",
            "message", "获取班级列表成功",
            "data", classes
        ));
    }

    @GetMapping("/teacher/classes/{id}")
    @Operation(summary = "教师获取班级详情", description = "教师根据ID获取班级详细信息")
    @PreAuthorize("hasRole('TEACHER')")
    public ResponseEntity<Map<String, Object>> getClassById(@PathVariable Long id) {
        ClassInfo classInfo = classService.findById(id);
        return ResponseEntity.ok(Map.of(
            "status", "success",
            "message", "获取班级详情成功",
            "data", classInfo
        ));
    }

    @PostMapping("/admin/classes")
    @Operation(summary = "创建班级", description = "管理员创建新的班级")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Map<String, Object>> createClass(@RequestBody ClassInfo classInfo) {
        ClassInfo savedClass = classService.save(classInfo);
        return ResponseEntity.ok(Map.of(
            "status", "success",
            "message", "创建班级成功",
            "data", savedClass
        ));
    }

    @PutMapping("/admin/classes/{id}")
    @Operation(summary = "更新班级", description = "管理员更新现有班级信息")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Map<String, Object>> updateClass(
            @PathVariable Long id, 
            @RequestBody ClassInfo classInfo) {
        classInfo.setId(id);
        ClassInfo updatedClass = classService.update(classInfo);
        return ResponseEntity.ok(Map.of(
            "status", "success",
            "message", "更新班级成功",
            "data", updatedClass
        ));
    }

    @DeleteMapping("/admin/classes/{id}")
    @Operation(summary = "删除班级", description = "管理员删除指定的班级")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Map<String, Object>> deleteClass(@PathVariable Long id) {
        classService.deleteById(id);
        return ResponseEntity.ok(Map.of(
            "status", "success",
            "message", "删除班级成功"
        ));
    }


} 